package vfs.persist;

import vfs.except.VFSException;
import vfs.obj.entity.VFSEntity;
import vfs.persist.entity.build.impl.VFSEntityBuilderImpl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 *
 * @author Matthew Eavenson <durandal@uga.edu>
 */
public class VFSIterator<T extends VFSEntity> implements Iterator<T> {

    private ResultSet rs;
    private VFSEntityBuilderImpl<T> builder;
    private T next;
    
    public VFSIterator(ResultSet rs, VFSEntityBuilderImpl<T> builder){
        this.rs = rs;
        this.builder = builder;
        next = null;
    }
    
       /*********************************************************************************
     * Indicate whether there are more rows in the result set.
     * @return  true if there are more rows, else false
     */
    public boolean hasNext ()
    {
        try{
            if(next == null){
                if(!rs.next()){
                    close();
                    return false;
                }else next = builder.build(rs);
            }
        }catch(SQLException sqe){
            sqe.printStackTrace();
            return false;
        }catch(VFSException ex){
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    /*********************************************************************************
     * Retrieve the next row as an array of objects.
     * @return  the next row
     */
    public T next(){
        if(!hasNext()) throw new NoSuchElementException();
        T obj = next;
        next = null;
        return obj;
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException("Remove is not supported for VFSEntities.");
    }
    
    public void close(){
        try{
           rs.getStatement().close();
           rs.close();
        }catch(SQLException sqe){
            sqe.printStackTrace();
        }
    }
    
}
